package cn.hsp.harmonyosdemos;

import cn.hsp.harmonyosdemos.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;

import static cn.hsp.harmonyosdemos.slice.MainAbilitySlice.REQUEST_CODE_READ_USER_STORAGE;

/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：花生皮编程
 */
public class MainAbility extends Ability {
    private MainAbilitySlice mainAbilitySlice;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());

        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.READ_USER_STORAGE")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                        new String[]{"ohos.permission.READ_USER_STORAGE"}, REQUEST_CODE_READ_USER_STORAGE);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
                new ToastDialog(getContext()).setText("请进入系统设置进行授权").show();
            }
        }
    }

    @Override
public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST_CODE_READ_USER_STORAGE: {
            if (grantResults.length > 0
                    && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                // 权限被授予之后做相应业务逻辑的处理
                mainAbilitySlice.showPhotos();
            } else {
                // 权限被拒绝
                new ToastDialog(getContext()).setText("权限被拒绝").show();
            }
        }
    }
}

    public void setMainAbilitySlice(MainAbilitySlice mainAbilitySlice) {
        this.mainAbilitySlice = mainAbilitySlice;
    }
}
